package org.example.aienglishapp_login.util.operationlog;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

public class LogUtils {

    // 获取当前用户名
    public static String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName(); // 返回当前用户的用户名
        }
        return "匿名用户"; // 返回匿名
    }

    // 获取当前请求路径
    public static String getArguments(Object[] args) {
        if (args == null) {
            return "null";
        }
        return Arrays.toString(args); // 将参数数组转换为字符串
    }

    public static String getClientIp() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String ip = request.getHeader("X-Forwarded-For"); // 支持代理服务器

            if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                // 如果存在多个 IP，取第一个
                String[] ips = ip.split(",");
                for (String i : ips) {
                    if (isIPv4(i.trim())) {
                        return i.trim(); // 返回 IPv4 地址
                    }
                }
            }

            // 获取客户端真实IP
            String remoteAddr = request.getRemoteAddr();
            if (isIPv4(remoteAddr)) {
                return remoteAddr; // 返回 IPv4 地址
            }

            // 如果是环回地址，将其转换为 IPv4 地址
            if ("0:0:0:0:0:0:0:1".equals(remoteAddr) || "localhost".equalsIgnoreCase(remoteAddr)) {
                return "127.0.0.1"; // 返回 localhost 的 IPv4 地址
            }

            return remoteAddr; // 返回其他地址
        }
        return "unknown"; // 默认值
    }

    // 辅助方法，检查是否为有效的 IPv4 地址
    private static boolean isIPv4(String ip) {
        String ipv4Pattern =
                "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                        "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                        "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                        "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        return ip.matches(ipv4Pattern);
    }
}